package iut2.server;

import iut2.shared.Troll;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;
import org.w3c.dom.Text;
import org.xml.sax.SAXException;

import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
 
public class XMLParser {

	ArrayList<Troll> build;
	File fXmlFile;
	
	public XMLParser(String file){
		try {
			fXmlFile = new File(file);		
		}
		catch (Exception e) {
			e.printStackTrace();
		}

	}
	
	private String getTagValue(String sTag, Element eElement)
	{		
		NodeList nlList = eElement.getElementsByTagName(sTag).item(0).getChildNodes();
		Node nValue = (Node) nlList.item(0);
		return nValue.getNodeValue();
	}
	
	public ArrayList<Troll> getTrollFromXML() throws ParserConfigurationException, SAXException, IOException
	{	
		build = new ArrayList<Troll>();
		
		DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
		DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
		Document doc = dBuilder.parse(fXmlFile);
		doc.getDocumentElement().normalize();
		
		NodeList nList = doc.getDocumentElement().getChildNodes();
		for (int temp = 0; temp < nList.getLength(); temp++) {
 
			Node nNode = nList.item(temp);
			if (nNode.getNodeType() == Node.ELEMENT_NODE) {
 
				Element eElement = (Element) nNode;
				
				Troll t = new Troll();
				t.setTroll(
					getTagValue("name", eElement).toString(),
					Integer.parseInt(getTagValue("attaque", eElement)),
					Integer.parseInt(getTagValue("degat", eElement)),
					Integer.parseInt(getTagValue("esquive", eElement)),
					Integer.parseInt(getTagValue("regeneration", eElement)),
					Integer.parseInt(getTagValue("ptn_de_vie", eElement)),
					getTagValue("race", eElement).toString(),
					Integer.parseInt(getTagValue("competence_1", eElement)),
					Integer.parseInt(getTagValue("competence_2", eElement)),
					getTagValue("image", eElement).toString()
				);
				build.add(t);
			}
		}
		
		return this.build;
	}
	
	public Boolean setTrollToXML(ArrayList<Troll> t) throws ParserConfigurationException, SAXException, IOException, TransformerFactoryConfigurationError, TransformerException
	{
		if( fXmlFile.exists() ) 
		{
			fXmlFile.delete();
			fXmlFile.createNewFile();
			FileWriter fw = new FileWriter(fXmlFile);
			fw.write("<?xml version=\"1.0\" ?>\n<trollList>\n</trollList>");
			fw.close();
		}
		
		DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
		DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
		
		Document doc = dBuilder.parse(fXmlFile);
		doc.getDocumentElement().normalize();
		
		Element root = (Element) doc.getElementsByTagName("trollList").item(0);		
		
	    for(int i=0; i<t.size(); i++)
	    {
	    	Element node = doc.createElement("troll");
	        node.setAttribute("id", String.valueOf(i));
	        
	        Element name  = doc.createElement("name");
	        Element attaque  = doc.createElement("attaque");
	        Element degat  = doc.createElement("degat");
	        Element esquive  = doc.createElement("esquive");
	        Element regeneration  = doc.createElement("regeneration");
	        Element ptn_de_vie  = doc.createElement("ptn_de_vie");
	        Element race  = doc.createElement("race");
	        Element competence_1  = doc.createElement("competence_1");
	        Element competence_2  = doc.createElement("competence_2");
	        Element image  = doc.createElement("image");
	        
	        Text textNode = doc.createTextNode(t.get(i).getName());
	        name.appendChild(textNode);
	        node.appendChild(name);
	        
	        textNode = doc.createTextNode(String.valueOf(t.get(i).getAttaque()));
	        attaque.appendChild(textNode);
	        node.appendChild(attaque);
	        
	        textNode = doc.createTextNode(String.valueOf(t.get(i).getDegat()));
	        degat.appendChild(textNode);
	        node.appendChild(degat);
	        
	        textNode = doc.createTextNode(String.valueOf(t.get(i).getEsquive()));
	        esquive.appendChild(textNode);
	        node.appendChild(esquive);
	        
	        textNode = doc.createTextNode(String.valueOf(t.get(i).getRegeneration()));
	        regeneration.appendChild(textNode);
	        node.appendChild(regeneration);
	        
	        textNode = doc.createTextNode(String.valueOf(t.get(i).getPtn_de_vie()));
	        ptn_de_vie.appendChild(textNode);
	        node.appendChild(ptn_de_vie);
	        
	        textNode = doc.createTextNode(t.get(i).getRace());
	        race.appendChild(textNode);
	        node.appendChild(race);
	        
	        textNode = doc.createTextNode(String.valueOf(t.get(i).getCompetence_1()));
	        competence_1.appendChild(textNode);
	        node.appendChild(competence_1);
	        
	        textNode = doc.createTextNode(String.valueOf(t.get(i).getCompetence_2()));
	        competence_2.appendChild(textNode);
	        node.appendChild(competence_2);
	        
	        textNode = doc.createTextNode(t.get(i).getImage_url());
	        image.appendChild(textNode);        
	        node.appendChild(image);
	        
	        root.appendChild(node);
	    }
	    
		
	    Transformer tr = TransformerFactory.newInstance().newTransformer();
        tr.setOutputProperty(OutputKeys.INDENT, "yes");
        tr.setOutputProperty(OutputKeys.METHOD, "xml");

        tr.transform(new DOMSource(doc), new StreamResult(new FileOutputStream(fXmlFile)));
		
		return true;
	}
}

